from frame_work.login import PcLogin
from frame_work.logger import Logger
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.util import check_tid, assert_result_dict, get_sql_info
from frame_work import menu_list

# logger = Logger(logger ='audit_order_or_report').get_logger()
logger = Logger(__name__).get_logger()


class Audit(object):
    def __init__(self, tid):
        self.tid = tid
        self.session = self.get_session()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_session(self):
        """
        返回session
        :return:
        """
        statement = """SELECT uname from sk_try where tid = %s"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询活动商家名称uname"
        })
        login = PcLogin(value[0].get("uname"))
        login.pc_login()
        session = login.get_session()
        return session

    def audit_no(self, uname):
        """
        审核单个试客的订单号
        :param uname:
        :return:
        """

        statement = """SELECT jid from sk_join where trade_no_state =2 and buyer_uname=%s and tid = %s"""
        params = (uname, self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询参与jid"
        })
        try:
            jid = value[0].get("jid")
        except Exception as e:
            logger.debug("没有待审核订单号，或者其它问题 %s" % e)
        else:
            yaml_data = self.yaml.get_data('audit_order')
            yaml_data.update({
                'data': {
                    "trade_info[%s]" % jid: 1
                }
            })
            logger.debug('开始审核订单号')
            response = self.session.post(
                yaml_data.get('url'),
                data=yaml_data.get('data'),
                headers=yaml_data.get('header')).text
            promote = response.encode('utf-8').decode('unicode_escape')
            assert_result_dict(promote, uname + '的订单号审核通过')

    def audit_all_no(self):
        """
        一键审核所有符合条件的订单号
        :return:
        """
        statement = """SELECT jid from sk_join where trade_no_state =2 and tid = %s"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询活动所有参与jid"
        })
        jids = []
        try:
            for jid_obj in value:
                jids.append(jid_obj.get("jid"))
        except Exception as e:
            logger.debug("没有待审核订单号，或者其它问题 %s" % e)
        else:
            tmp_dict = {}
            yaml_data = self.yaml.get_data('audit_all_order')
            for jid in jids:
                tmp_dict.update({"trade_info[%s]" % jid: 1})
            yaml_data.update({
                'data': tmp_dict
            })
            logger.debug('开始审核所有符合条件的订单号')
            response = self.session.post(
                yaml_data.get('url'),
                data=yaml_data.get('data'),
                headers=yaml_data.get('header')).text
            promote = response.encode('utf-8').decode('unicode_escape')
            assert_result_dict(promote, '该活动所有的待审核订单号审核通过')

    def audit_report(self, uname):
        """
        审核通过单个报告
        :param uname:
        :return:
        """
        statement = """SELECT rid from sk_report where state =2 and buyer_uname = %s and tid = %s"""
        params = (uname, self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询报告rid"
        })
        try:
            rid = value[0].get("rid")
        except Exception as e:
            logger.debug("没有待审核报告，可能订单号还没审核或者其它问题 %s" % e)
        else:
            yaml_data = self.yaml.get_data('audit_report')
            logger.debug('开始审核报告')
            response = self.session.post(
                url=yaml_data.get('url') + "?rid=" + str(rid),
                headers=yaml_data.get('header')).text
            promote = response.encode('utf-8').decode('unicode_escape')
            assert_result_dict(promote, uname + '的报告审核通过')

    def audit_all_report(self):
        """
        一键审核所有符合条件的报告
        :return:
        """
        try:
            statement = """SELECT jid,buyer_uname from sk_join where tid = %s and trade_no_state =3 and report_state = 2"""
            params = (self.tid,)
            value = get_sql_info(statement, params, meta={
                "info": "查询所有参与的报告rid"
            })
            unames = []
            jids = []
            for obj in value:
                jid = obj.get("jid")
                uname = obj.get("buyer_uname")
                unames.append(uname)
                jids.append(jid)
        except Exception as e:
            logger.debug("没有符合条件的报告可审核: %s..." % e)
        else:
            yaml_data = self.yaml.get_data('audit_all_report')
            yaml_data.get('data').update({
                'jids[]': jids,
                'names[]': unames
            })
            logger.debug('开始审核所有符合条件的报告')
            response = self.session.post(
                yaml_data.get('url'),
                data=yaml_data.get('data'),
                headers=yaml_data.get('header')).text
            promote = response.encode('utf-8').decode('unicode_escape')
            assert_result_dict(promote, '该活动的待审核报告全部审核通过')


def main():
    while True:
        # 显示功能菜单
        menu_list.audit_no_report_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            audit = Audit(tid)
            if choise == '1':
                buyer_uname = input('请输入您待审核订单号的试客账户:\n')
                audit.audit_no(buyer_uname)
            elif choise == '2':
                buyer_uname = input('请输入您待审核报告的试客账户:\n')
                audit.audit_report(buyer_uname)
            elif choise == '3':
                audit.audit_all_no()
            elif choise == '4':
                audit.audit_all_report()
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == '__main__':
    main()
